package com.itheima.health.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.entity.Result;
import com.itheima.health.service.SetmealService;
import com.itheima.health.utils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @Reference
    private SetmealService setmealService;

    /**
     * 图片上传
     *
     * @param file 图片上传组件
     * @return
     */
    @RequestMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file) {
        try {
            // 获取原图片文件名
            String fileName = file.getOriginalFilename();
            // 文件名的基础上，在前面加入UUID，防止文件重名
            String saveUploadName = UUID.randomUUID().toString().replace("-", "") + "_" + fileName;
            // 使用七牛工具类，完成图片上传
            QiniuUtils.upload2Qiniu(file.getBytes(), saveUploadName);
            // 把访问路径返回给客户端
            String file_url = QiniuUtils.qiniu_img_url_pre + saveUploadName;
            // 把全路径返回给客户端
            return new Result(true, MessageConst.PIC_UPLOAD_SUCCESS, file_url);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConst.PIC_UPLOAD_FAIL);
        }
    }

    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        try {
            PageResult pageResult = setmealService.pageQuery(queryPageBean.getCurrentPage(), queryPageBean.getPageSize(), queryPageBean.getQueryString());
            return new PageResult(pageResult.getTotal(),pageResult.getRows());
        }catch (Exception e){
            e.printStackTrace();
        }
        return new PageResult(0L,null);
    }

}
